package com.pks.autoInsurance.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.pks.autoInsurance.dto.RegistrationDto;

/**
 * Implementation class for LoginDAO
 * 
 * @author Pankaj Soni
 * 
 */
public class LoginDAOImpl extends AutoInsuranceDAO implements LoginDAO {
	/**
	 * Performs login authentication and authorisation for the user.
	 * 
	 * @see com.cts.autoInsurance.dao.LoginDAO#authenticateUser(com.cts.autoInsurance
	 *      .dto.RegistrationDtoReq)
	 */
	@Override
	public int authenticateUser(RegistrationDto registrationReq) {
		System.out.println(getClass() + "::::authenticateUser::::begin");
		final Connection connection = getConnection();
		final String sql = "SELECT SSN,PASSWD FROM REGISTRATION WHERE SSN=? AND PASSWD=?";
		try {
			connection.setAutoCommit(false);
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, registrationReq.getSsn());
			preparedStatement.setString(2, registrationReq.getPasswd());
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				if (resultSet.getString("SSN").equalsIgnoreCase("adminadmin")) {
					return VALID_ADMIN;
				}
				return VALID_USER;
			}

		} catch (SQLException e) {
			System.err.println(getClass() + "::::" + e.getMessage());
			return INVALID_USER;
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				System.err.println(getClass() + "::::" + e.getMessage());
			}
		}
		System.out.println(getClass() + "::::authenticateUser::::end");
		return INVALID_USER;
	}

}
